# coding=utf-8

from application import app
import hashlib, requests,random,string,json, urllib

"""
腾讯地图API接入
"""
class MapLibs():
    def __init__(self):
        self.key = app.config["TENCENT_MAP"]["KEY"]
        self.sk = app.config["TENCENT_MAP"]["SK"]

    def __request__(self, queryStr):
        url = self.url_coder(queryStr)
        r = requests.get(url)
        res = json.loads(r.text)
        if int(res["status"]) == 0:
            return res["result"]
        return None

    def geocoder(self, latitude, longitude):
        """
        坐标反编码  经纬度换具体信息
        :param latitude:
        :param longitude:
        :return:
        """
        queryStr = """/ws/geocoder/v1?get_poi=0&location=%s,%s&key=%s""" % (latitude, longitude, self.key)
        res = self.__request__(queryStr)
        return res


    def url_coder(self, queryStr):
        #
        """
        把url转码成为可以解析的格式
        :param queryStr:
        :return:
        """
        domain = """https://apis.map.qq.com"""
        sn = self.get_sn(queryStr)
        url = urllib.parse.quote(domain + queryStr + "&sn=" + sn, safe="/:=&?#+!$,;'@()*[]")
        return url

    def get_sn(self, queryStr):
        """
        计算SN
        :param queryStr:
        :return:
        """
        encodedStr = urllib.parse.quote(queryStr, safe="/:=&?#+!$,;'@()*[]")
        rawStr = encodedStr + self.sk
        rawStr = urllib.parse.quote_plus(rawStr).encode("utf8")
        sn = hashlib.md5(rawStr).hexdigest()
        return sn

    def getlist(self):
        queryStr = """/ws/district/v1/list?key=%s""" % (self.key)
        res = self.__request__(queryStr)
        return res